import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import VuexORM from '@vuex-orm/core';
import VuexORMAxios from '@vuex-orm/plugin-axios';
import database from '../database';
import getters from './getters';
import { auth } from './auth.module';
import authHeader from '../services/auth-header';
import defaultSettings from '../settings';

Vue.use(Vuex);

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/);

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
    // set './app.js' => 'app'
    const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1');
    const value = modulesFiles(modulePath);
    modules[moduleName] = value.default;
    return modules;
}, {});

VuexORM.use(VuexORMAxios, {
    axios,
    headers: authHeader(),
    baseURL: defaultSettings.baseURL,
    dataKey: 'data'
});

const store = new Vuex.Store({
    modules,
    getters,
    auth,
    plugins: [VuexORM.install(database)]
});

export default store;
